package edu.spbu.eclipse.addressbook.andrpodk;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;
import java.util.*;


public class Viewer {	
	private Table table;
	private ArrayList<Integer> findResults;
	private int nextFindResult;

	public Viewer(Composite parent){			
		table=new Table(parent,SWT.FULL_SELECTION);		
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		TableColumn name=new TableColumn(table,SWT.LEFT);
		name.setWidth(180);
		name.setText("Name");
		TableColumn telephone=new TableColumn(table,SWT.LEFT);
		telephone.setWidth(130);
		telephone.setText("Telephone");
		TableColumn e_mail=new TableColumn(table,SWT.LEFT);
		e_mail.setWidth(160);
		e_mail.setText("E-mail");
		TableColumn address=new TableColumn(table,SWT.LEFT);
		address.setWidth(200);
		address.setText("Address");
	}

	public void show(ArrayList<Entry> addressBook){
		table.removeAll();
		int s=addressBook.size();		
		for(int i=0;i<s;i++){
			TableItem item=new TableItem(table,SWT.NONE);			
			item.setText(addressBook.get(i).toStringArray());
		}
		table.select(0);		
	}

	public void refreshAdded(ArrayList<Entry> addressBook,int i){		
		TableItem item=new TableItem(table,SWT.NONE,i);
		item.setText(addressBook.get(i).toStringArray());
		table.select(i);		
	}

	public void refreshChanged(ArrayList<Entry> addressBook,int oldIndex,int newIndex){
		table.remove(oldIndex);
		TableItem item=new TableItem(table,SWT.NONE,newIndex);
		item.setText(addressBook.get(newIndex).toStringArray());
		table.select(newIndex);		
	}

	public void refreshDeleted(int i){
		table.remove(i);
		table.select(0);		
	}

	public int getSelected(){
		return table.getSelectionIndex();		
	}
	public boolean find(String string){
		String stringLow=string.toLowerCase();
		findResults=new ArrayList<Integer>();
		int size=table.getItemCount();
		TableItem item;
		for(int i=0;i<size;i++){
			item=table.getItem(i);
			for(int j=0;j<4;j++){
				String field=item.getText(j).toLowerCase();
				if(field.indexOf(stringLow)!=-1){
					findResults.add(new Integer(i));
					break;
				}				
			}			
		}	
		if((size=findResults.size())!=0){
			table.select(findResults.get(0));
			nextFindResult=1%size;			
			return true;
		}else{
			return false;
		}
	}

	public void findNext(){
		table.select(findResults.get(nextFindResult));
		nextFindResult=++nextFindResult%findResults.size();
	}

	public void setFocus() {
		table.setFocus();		
	}
}